<?php
/**
 * Created by PhpStorm.
 * User: bill
 * Date: 2014/12/2
 * Time: 9:55
 */
class C发微信消息 extends  CBS
{

    public $id;
    public $user;
    public $公众号;
    public $权限;
    public $voCenter;


    function __construct(){
        parent::__construct();
        $this->voCenter = $this->fs实例化信息中心('');

    }


    public function fc查看课程即将开课($时间限制) {

        $sql= "SELECT * FROM 语音课程 WHERE `开始时间`  BETWEEN  '".date('Y-m-d H:i:s')."' and '".$时间限制."'   ";

        $课程=  pdo()->selectAll($sql);
        if(!$课程) return false;

        foreach($课程 as $key=>$value){

            $this->fs给报名课程的用户发送消息($value);

        }

        #Cx消息路由::ff处理返回堆栈();
    }

    public function f推送单个课程消息($课程id) {
        $sql = sprintf("SELECT * FROM 语音课程 WHERE id = '%s'", $课程id);
        $课程 = pdo()->selectOne($sql);
        if ($课程) {
            $this->fs给报名课程的用户发送消息($课程);
        }
    }

    public function fs给报名课程的用户发送消息($课程) {
        if ($课程['is_test']) {
            $用户信息 =  $this->fh获取测试用户();
        } else {
            $用户信息 =  $this->fh获取当前报名该课程的用户($课程['id']);
        }

        $url = Tools::url('course','course_detail', array('id' => $课程['id']));

        $voCenter = $this->fs实例化信息中心('');

        foreach ($用户信息 as $value) {
            $图文信息 = $voCenter->vc微直达->给用户发送语音课程信息("视频课程将要开始",'课程《'.$课程['title'].'》将要开始，请按时进入课堂!',$课程['id']);

            $m模板信息 = array(
                'id' => $课程['id'],
                '咨询模板ID' => $课程['course_notice_templateId'],
                'userName' => $value['name'],
                'courseName' => $课程['title'],
                'date' => $课程['开始时间'],
                'remark' => $课程['简介'],
            );

            $模板类型 = '开课通知';
            $this->fs发送咨询课程_图文模板信息($图文信息, $value, $m模板信息, $模板类型, $url);

        }
        return true;
    }

    function f页面链接($文件名, $va参数) {
        $va参数['publicnumber'] = G_SERV_ID;
        $state=Tools::pack参数打包($文件名,$va参数);
        $url = G_SITE_BASE . '/business/index.php?state='.$state;
        return $url;
    }

    function f页面链接_new($m,$a, $parm) {
        $url=Tools::url($m,$a,$parm);

        // $va参数['publicnumber'] = G_SERV_ID;
        // $state=Tools::pack参数打包($文件名,$va参数);
        // $url = G_SITE_BASE . '/business/index.php?state='.$state;
        return $url;
    }

    function fh获取测试用户() {
        $sql = "SELECT b.`name`,b.openID,b.`公众号ID`,b.`公众号openID` FROM  `test_user` a LEFT JOIN `用户` b on(a.`openId` = b.openId)";
        return pdo()->selectAll($sql);
    }

    public function fh获取当前报名该课程的用户($课程id) {
        if (!empty($_POST['oid'])) {
            #发给单个测试人员
            $sql = sprintf("SELECT a.`课程id`,b.`name`,b.openID,b.`公众号ID`,b.`公众号openID` FROM  `语音课程报名` a LEFT JOIN `用户` b on(a.`用户id` = b.id) WHERE a.`课程id`= '%s' and b.openID = '%s' and a.`状态` = '报名' group by b.openID", $课程id, $_POST['oid']);
        } else {
            $sql = sprintf("SELECT a.`课程id`,b.`name`,b.openID,b.`公众号ID`,b.`公众号openID` FROM  `语音课程报名` a LEFT JOIN `用户` b on(a.`用户id` = b.id) WHERE a.`课程id`= '%s' and a.`状态` = '报名' group by b.openID", $课程id);
        }
        Logger::getInstance()->logInfo("获取当前报名该课程的用户sql:". $sql);
        $用户 = pdo()->selectAll($sql);
        return $用户;
    }


    public  function fc判断当前时间内专家有课($专家id,$开始时间,$结束时间,$课程id =0){
        $sql = "SELECT count(a.`id`) as `num`  FROM `语音课程报名` a LEFT JOIN `语音课程` b  ON a.`课程id`=b.id WHERE a.`用户id` ='".$专家id."'   AND   b.`状态` !='结束'  AND b.id != '".$课程id."'
 AND a.`状态`='报名' AND ( b.`开始时间` between  '".$开始时间."' AND '".$结束时间."' OR  b.`结束时间` between   '".$开始时间."' AND '".$结束时间."');";
        $时间冲突 = pdo()->selectAll($sql);
        return $时间冲突[0]['num'];
    }

    public function fc发送图文消息_所有用户($类别, $课程id, $用户oid =null, $limit = 0, $size = 1000){
        $url = Tools::url('course','course_detail', array('id' => $课程id));
        $课程详情 = pdo()->selectOne("SELECT a.*,b.`name` FROM `语音课程` a LEFT JOIN `用户` b on(a.`讲课专家id` = b.id) WHERE a.id='".$课程id."' ");
        $图文信息=$this->voCenter->vc微直达->给用户发送语音课程信息($类别,$课程详情['theme'],$课程id);
        $数据表 = '课程';
        $this->ff发送咨询信息过程($图文信息,$课程详情,$数据表,$url,$用户oid, $limit, $size);
        return true;
    }

    //发送最美医生投票推送
    public function send_vote($vote_id, $user_oid=null, $limit = 0, $size = 1000) {

        $voCenter = $this->fs实例化信息中心($user_oid);
        $url = Tools::url('vote', 'index',array('id'=>$vote_id));
        $doctor_deatail = pdo()->selectColumns("vote_beautiful_doctor",array('*'),array('id'=>$vote_id));
        $图文信息 = $voCenter->vc微直达->添加要图文信息1($doctor_deatail);

        $数据表 = '投票';
        $m模板信息 = $doctor_deatail;
        $this->ff发送咨询信息过程($图文信息,$m模板信息,$数据表,$url,$user_oid, $limit, $size);
    }

    //判断咨询类型，普通咨询，课程回顾
    function is_exits_case($zixun_id){
        $do = new Do咨询详情();
        $do->set_咨询id($zixun_id);
        $re = $do->where($do->data)->rows();
        foreach($re as $k => $v) {
            if($v['news_type'] == 2){
                return '2';
            }
        }
        return '1';
    }

    public function ff发送咨询信息($咨询id,$用户oid =null, $limit = 0, $size = 1000){

        $news_type = $this->is_exits_case($咨询id);

        if($news_type == '1'){
            $url = Tools::url('iread', 'index');
        }else{
            $url = Tools::url('course', 'course_history');

        }

        $m模板信息 = pdo()->selectColumns("咨询信息",array('*'),array('id'=>$咨询id));
        $do = new Do咨询详情();
        $咨询详情 = pdo()->selectBOs($do,array("咨询id"=>$咨询id),'',' order by `排序` ');

        $图文信息 = $this->voCenter->vc微直达->添加要图文信息($咨询详情);
        $数据表 = '咨询';

        $this->ff发送咨询信息过程($图文信息,$m模板信息,$数据表,$url,$用户oid, $limit, $size);
    }

    private function ff发送咨询信息过程($图文信息,$m模板信息,$数据表,$url,$用户oid, $limit = 0, $size = 1000){

        #发给单个测试用户
        if($用户oid){
            $statement = pdo()->prepare_execute("select name, openID,id,公众号ID,公众号openID from 用户 where 公众号ID = ? AND  openID =? ORDER BY id",array(G_SERV_ID,$用户oid));

            #测试课程只发给测试人员
        } elseif ($数据表 == '课程' and $m模板信息['is_test'] == '1') {
            $statement = pdo()->prepare_execute("select u.name, u.openID,u.id,u.公众号ID,u.公众号openID from test_user t left join 用户 u on t.openID = u.openID where u.公众号ID = ? AND u.unsubscribe = 0 ORDER BY u.id",array(G_SERV_ID));

            #发给全部用户
        } else {
            $statement = pdo()->prepare_execute("select name, openID,id,公众号ID,公众号openID from 用户 where id >= ? and id < ? AND unsubscribe = 0  ORDER BY id", array($limit, $limit + $size));
        }

        if (false == $statement) {
            logger::getInstance()->logDebug2("选用户发图文消息出错");
            return false;
        }

        while(true) {
            $data = $statement->fetch(PDO::FETCH_ASSOC);

            if ($data == false){
                break; //无结果
            }
            $this->fs发送咨询课程_图文模板信息($图文信息,$data,$m模板信息,$数据表,$url);
        }
    }

    private function  fs发送咨询课程_图文模板信息($图文信息,$data,$m模板信息,$数据表,$url){

        #判断是否成功发送过
        $do消息发送记录 = new Do消息发送记录();
        $do消息发送记录->set_接收消息用户openID($data['openID']);
        $do消息发送记录->set_信息id($数据表.$m模板信息['id']);
        $do消息发送记录->set_是否正确发送('是');
        $is_receive_msg = $do消息发送记录->where($do消息发送记录->data)->count();

        #判断是否是测试人员
        $do_test_user = new DoTest_user();
        $do_test_user->set_openId($data['openID']);
        $is_test_user = $do_test_user->where($do_test_user->data)->count();

        #非测试人员只能收一条消息
        if ($is_receive_msg and !$is_test_user) {
            return true;
        }

        $发送图文返回 = $this->voCenter->ff发送图文消息($图文信息,$data['openID']);
        $发送图文返回 = json_decode($发送图文返回);

        if($发送图文返回->errmsg != 'ok') {
            if($数据表=='课程') {
                $发送模板返回 = $this->fs发送课程提醒模板($data['openID'], $m模板信息, $url);
            } elseif ($数据表=='开课通知') {
                $发送模板返回 = $this->fs发送_课程开课通知_模板($data['openID'], $m模板信息, $url);
            } elseif($数据表=='投票'){
                $发送模板返回 = $this->fs发送审核提醒模板($data['openID'], $m模板信息, $url);
            } elseif($数据表=='会议视频'){
                $发送模板返回 = $this->send_meet_video_template($data['openID'], $m模板信息, $url);
            }
            else{

                $发送模板返回 = $this->fs发送作业消息模板($data['openID'], $m模板信息, $url);
            }

            if($发送模板返回->errmsg == 'ok'){
                $this->fs发送信息记录($data,'作业消息模板','是',$发送模板返回->errcode,$m模板信息['标题'],$data['公众号ID'],$data['公众号openID'],$数据表.$m模板信息['id']);
            } else {
                $this->fs发送信息记录($data,'作业消息模板','否',$发送模板返回->errcode,$m模板信息['标题'] ,$data['公众号ID'],$data['公众号openID'],$数据表.$m模板信息['id']);
            }


        } else {
            $this->fs发送信息记录($data,'图文消息','是',$发送图文返回->errcode ,$m模板信息['标题'] ,$data['公众号ID'],$data['公众号openID'],$数据表.$m模板信息['id']);
        }

    }

    /**
     * @param $用户oid
     * @return bool|C信息中心
     */
    private function fs实例化信息中心($openid) {
        if (!$openid) $openid = G_DEFAULT_USER_OPENID;
        $voCenter = C信息中心::get实列根据用户Oid($openid);
        return $voCenter;
    }

    public function send_meet_video_template($openID, $模板信息, $url){
        global $G_CONFIG;
        $模板信息['咨询模板ID'] = trim($G_CONFIG['模板消息ID']['会议视频通知']);
        $发送模板结果= $this->voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'first'=>array('value'=> "《".$模板信息['name']."》会议视频已发布",'color'=>'#173177'),
            'keyword1'=>array('value'=>'会议视频','color'=>'#173177'),
            'keyword2'=>array('value'=> "已上线",'color'=>'#173177'),
            'remark'=>array('value'=> '欢迎观看','color'=>'#173177')

        ), G_SERV_ID,$url);

        return $发送模板结果;
    }

    public function fs发送审核提醒模板($openID, $模板信息, $url){
        $模板信息['咨询模板ID'] = trim($模板信息['modle_id']);
        $发送模板结果= $this->voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'first'=>array('value'=> "开始投票啦，期待您的参与~",'color'=>'#173177'),
            'keyword1'=>array('value'=>'寻找最美儿科医生','color'=>'#173177'),
            'keyword2'=>array('value'=> $模板信息['release_date'],'color'=>'#173177'),
            'remark'=>array('value'=> $模板信息['descript'],'color'=>'#173177')

        ), G_SERV_ID,$url);

        return $发送模板结果;
    }

    public function fs发送作业消息模板($openID, $模板信息, $url){
        $模板信息['咨询模板ID'] = trim($模板信息['咨询模板ID']);
        $发送模板结果= $this->voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'first'=>array('value'=> $模板信息['标题']."\n",'color'=>'#5C94C6'),
            'keyword1'=>array('value'=>$模板信息['消息类别'],'color'=>'#CCCCCC'),
            'keyword2'=>array('value'=> $模板信息['发布人'],'color'=>'#CCCCCC'),
            'keyword3'=>array('value'=> $模板信息['发布时间'],'color'=>'#CCCCCC'),
            'remark'=>array('value'=> "\n".$模板信息['追加'],'color'=>'#A6A6A6')
        ), G_SERV_ID,$url);

        return $发送模板结果;
    }

    public function fs发送课程提醒模板($openID, $模板信息, $url){
        $模板信息['咨询模板ID'] = trim($模板信息['咨询模板ID']);
        $发送模板结果= $this->voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'first'=>array('value'=> "开课啦！点击立即报名！\n",'color'=>'#999999'),
            'keyword1'=>array('value'=>$模板信息['title'],'color'=>'#d0274a'),
            'keyword2'=>array('value'=> $模板信息['name'],'color'=>'#333333'),
            'remark'=>array('value'=> "\n".$模板信息['theme'],'color'=>'#5c94c6')
        ),G_SERV_ID,$url);

        return $发送模板结果;
    }

    public function fs发送_课程开课通知_模板($openID, $模板信息, $url) {
        $模板信息['咨询模板ID'] = trim($模板信息['咨询模板ID']);
        $发送模板结果= $this->voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'userName'=>array('value'=> $模板信息['userName'],'color'=>'#173177'),
            'courseName'=>array('value'=>$模板信息['courseName'],'color'=>'#173177'),
            'date'=>array('value'=> $模板信息['date'],'color'=>'#173177'),
            'remark'=>array('value'=>$模板信息['remark'],'color'=>'#173177')
        ),G_SERV_ID,$url);

        return $发送模板结果;
    }

    private  function fs发送信息记录($data,$type,$结果,$错误代码,$content,$公众号ID,$公众号openID,$信息id,$id =null){
        $接收消息用户openID = $data['openID'];
        $do = new Do消息发送记录();
        $do->set_id($id);
        $do->set_接收消息用户openID($接收消息用户openID);
        $do->set_消息类型($type);
        $do->set_发送时间(Date('Y-m-d H:i:s'));
        $do->set_是否正确发送($结果);
        $do->set_错误代码($错误代码);
        $do->set_消息内容($content);
        $do->set_公众号ID($公众号ID);
        $do->set_公众号openID($公众号openID);
        $do->set_信息id($信息id);
        $do->set_name($data['name']);
        $do->save();

        if ($错误代码 == '43004') {
            $doUser = new Do用户();
            $doUser->set_unsubscribe(1);
            $doUser->update(array('openID' => $接收消息用户openID));
            Logger::getInstance()->logInfo("用户已取消关注 openid：".$接收消息用户openID);
        }

    }

    public function get未认证医师列表($act,$当前页,$参数,$关键词){
        $where = null;
        if(!Empty($关键词)) {
            $where ="  and  b.name like '%$关键词%' ";
        }
        if($act == '1'){
            $状态='待审核';
        }else if($act == '2'){
            $状态='未通过';
        }else if($act == '3'){
            $状态='通过';
        }
        $sql = "select a.*, b.`头像`,c.区域 as 区域 from 医师详情 a LEFT JOIN `用户` b ON(b.id = a.用户id) left join 区域 as c on a.区域id = c.id  WHERE   a.状态='{$状态}' $where and b.公众号id ='". G_SERV_ID ."'  order by a.id desc ";

        return pdo()->page($sql,$当前页,10,$参数);
    }


    function  发送文字通知($infoUser,$openid,$公众号id){
        $voCenter=C信息中心::get实列根据用户Oid($openid);
        $voCenter->ff发送文本消息_多公众号($infoUser,$openid,$公众号id);
        $res = Cx消息路由::ff处理返回堆栈();
    }



    public function ff发送病例回复通知文本消息($openid,$caseId,$病历文章) {
        $url = $this->f页面链接('Seller19BingliAS_show', array('id' => $caseId));
        $infoUser = "您参与的病例讨论有新回复啦！<a href='$url'>点此查看</a>";
        $res = $this->voCenter->ff发送文本消息($infoUser,$openid);
        $result = json_decode($res);
        if($result->errmsg!="ok"){
            $this->ff病例回复模板消息($openid,$url,$病历文章);
        }
    }

    public function ff发送病例回复通知文本消息_new($openid,$caseId,$病历文章) {
        $url = $this->f页面链接_new('case', 'case_detail',array('id' => $caseId));
        $infoUser = "您参与的病例讨论有新回复啦！<a href='$url'>点此查看</a>";
        $res = $this->voCenter->ff发送文本消息($infoUser,$openid);
        $result = json_decode($res);
        if($result->errmsg!="ok"){
            $this->ff病例回复模板消息($openid,$url,$病历文章);
        }
    }

    public function ff病例回复模板消息($openID,$url,$病历文章) {
        $info = '您好！您参与的病例讨论有了新回复，点击查看';
        global $G_CONFIG;
        $date = date("Y-m-d H:i:s",time());
        $模板信息 = array(
            '咨询模板ID' => $G_CONFIG['模板消息ID']['问题回复通知'],
            'title' => $info,
            'content' => $病历文章['title'],
            'date' => $date,
        );
        $模板信息['咨询模板ID'] = trim($模板信息['咨询模板ID']);
        $发送模板结果= $this->voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'first'=>array('value'=> $模板信息['title'],'color'=>'#173177'),
            'keyword1'=>array('value'=>$模板信息['content'],'color'=>'#173177'),
            'keyword2'=>array('value'=> $模板信息['date'],'color'=>'#173177')
        ), G_SERV_ID,$url);

        return $发送模板结果;
    }

    public function ff发送医师审核文本消息($infoUser,$user,$status) {
        $res = $this->voCenter->ff发送文本消息($infoUser,$user['openID']);
        $msg = '医师审核文本消息';
        $result = json_decode($res);
        $send_result = '是';
        $errcode = $result->errcode;
        if($result->errmsg!="ok"){
            $msg = '医师审核模板消息';
            $res = $this->ff认证模板消息($infoUser,$status,$user['openID']);
            $errcode = $res->errcode;
            if($res->errmsg != 'ok'){
                $send_result = '否';
            }
        }
        if($status == '未通过'){
            $this->fs发送信息记录($user,$msg,$send_result,$errcode ,$infoUser ,$user['公众号ID'],$user['公众号openID'],'医师审核未通过');
        }
    }

    public function ff认证模板消息($infoUser,$status,$openID){
        global $G_CONFIG;
        $date = date("Y-m-d H:i:s",time());
        $info = preg_replace('/\\\n/','，',$infoUser);
        $模板信息 = array(
            '咨询模板ID' => $G_CONFIG['模板消息ID']['审核结果通知'],
            'title' => $info,
            'content' => "认证服务",
            'result' => $status,
            'remark' => $date,
        );
        $模板信息['咨询模板ID'] = trim($模板信息['咨询模板ID']);
        $发送模板结果= $this->voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'first'=>array('value'=> $模板信息['title'],'color'=>'#173177'),
            'keyword1'=>array('value'=>$模板信息['content'],'color'=>'#173177'),
            'keyword2'=>array('value'=> $模板信息['result'],'color'=>'#173177'),
            'remark'=>array('value'=>$模板信息['remark'],'color'=>'#173177')
        ), G_SERV_ID,'');

        return $发送模板结果;
    }

    //推送会议视频消息
    public function send_meet_video_message($meet_id, $user_oid=null, $limit = 0, $size = 1000) {

        $voCenter = $this->fs实例化信息中心($user_oid);
        $url = Tools::url('conference', 'common_shipinList',array('meet_shipin_id'=>$meet_id));
        $meet = pdo()->selectColumns("会议表",array('*'),array('id'=>$meet_id));
        $图文信息 = $voCenter->vc微直达->add_meet_message($meet, $url);

        $数据表 = '会议视频';
        $m模板信息 = $meet;
        $this->ff发送咨询信息过程($图文信息,$m模板信息,$数据表,$url,$user_oid, $limit, $size);
    }
}